package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.SysTag;
import com.ruoyi.system.mapper.SysTagMapper;
import com.ruoyi.system.service.ISysTagService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysTagServiceImpl implements ISysTagService {
    private static final Logger log = LoggerFactory.getLogger(SysTagServiceImpl.class);

    @Autowired
    private SysTagMapper sysTagMapper;


    public List<SysTag> getList(SysTag sysTag) {
        List<SysTag> list = new ArrayList<>();
        list = sysTagMapper.getList(sysTag);
        return list;
    }


    @Override
    public List<SysTag> getTreeList() {
        SysTag tag = new SysTag();
        List<SysTag> list = sysTagMapper.getList(tag);
        //顶级节点
        List<SysTag> parent = list.stream().filter(f -> f.getParentId() == 0).collect(Collectors.toList());
        for (SysTag sysTag : parent) {
            //判断是否是顶级节点
            if (sysTag.getParentId() == 0) {
                //遍历子代
                List<SysTag> childre = new ArrayList<>();
                for (SysTag child : list) {
                    if (sysTag.getId().equals(child.getParentId())) {
                        //添加子代到list
                        childre.add(child);
                        getChildrenList(childre, list);
                    }
                }
                //将子代添加到父代中
                sysTag.setChildren(childre);
            }
        }

        return parent;
    }


    public void getChildrenList(List<SysTag> childre, List<SysTag> list) {
        if (childre.size() == 0) {
            return;
        }
        childre.forEach(child -> {
            //遍历子代
            List<SysTag> childre2 = new ArrayList<>();
            for (SysTag child2 : list) {
                if (child.getId().equals(child2.getParentId())) {
                    //添加子代到list
                    childre2.add(child2);
                    getChildrenList(childre2, list);
                }
            }
            child.setChildren(childre2);
        });
    }

    @Override
    public Integer insert(SysTag sysTag) {
        return sysTagMapper.insertSysTag(sysTag);
    }

    @Override
    public Integer updateById(SysTag sysTag) {
        return sysTagMapper.updateById(sysTag);
    }

    @Override
    public Integer deleteById(Integer id) {
        return sysTagMapper.deleteById(id);
    }


}
